package test;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * http客户端
 */
public class HiCloudToken {

    public static void main(String[] args) throws IOException {
        String token = getHiCloudToken();
        String result = HttpRequest.get("https://mpc.cn-north-4.myhuaweicloud.com/v1/0c6810e985800f402fe8c01f591baf5c/template/transcodings")
                .body("page=0&size=10").bearerAuth(token).execute().body();
        System.out.println("result = " + result);
    }

    public static String getHiCloudToken() throws IOException {

        String result = "";
        String url = "https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens";
        //IAM用户所属账号名。
        String auth_identity_password_user_domain_name = "hw69509111";
        //IAM用户名
        String auth_identity_password_user_name = "hw69509111";
        //IAM用户的登录密码
        String auth_identity_password_user_password = "wang1007862826";
        //IAM用户所属账号的项目ID
        String auth_scope_project_id = "0c6810e985800f402fe8c01f591baf5c";
        //IAM用户所属账号的项目名称
        String auth_scope_project_name = "cn-north-4";
        JSONObject jsonParams = new JSONObject();
        JSONObject auth = new JSONObject();
        JSONObject identity = new JSONObject();
        JSONObject scope = new JSONObject();
        JSONArray methods = new JSONArray();
        JSONObject password = new JSONObject();
        JSONObject user = new JSONObject();
        JSONObject domain = new JSONObject();
        JSONObject project = new JSONObject();
        jsonParams.put("auth", auth);
        auth.put("identity", identity);
        auth.put("scope", scope);
        identity.put("methods", methods);
        identity.put("password", password);
        scope.put("project", project);
        methods.add("password");
        password.put("user", user);
        project.put("id", auth_scope_project_id);
        project.put("name", auth_scope_project_name);
        user.put("domain", domain);
        user.put("name", auth_identity_password_user_name);
        user.put("password", auth_identity_password_user_password);
        domain.put("name", auth_identity_password_user_domain_name);
        CloseableHttpResponse response = null;
        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        // 设置参数到请求对象中
        StringEntity stringEntity = new StringEntity(jsonParams.toString(), Charset.forName("UTF-8"));
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(stringEntity);
        // 执行请求操作，并拿到结果（同步阻塞）
        response = httpClient.execute(httpPost);
        // 获取结果实体
        // 判断网络连接状态码是否正常(0--200都数正常)
        Date date = null;
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == 201) {
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject parseObject = JSON.parseObject(result).getJSONObject("token");
            String dateString = parseObject.getString("expires_at");
            dateString = getDateTime(dateString);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                date = df.parse(dateString);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        String token = response.getHeaders("X-Subject-Token")[0].toString();
        token = token.substring(token.lastIndexOf(":") + 1);

        return token;
    }

    /**
     * 2020-09-25T02:44:48.457000Z
     *
     * @param dateString
     * @return
     */
    private static String getDateTime(String dateString) {
        // TODO Auto-generated method stub
        String[] arr = dateString.split("T");
        String substring = arr[1].substring(0, arr[1].lastIndexOf("."));
        return arr[0] + " " + substring;
    }

}


